from flask import Blueprint, render_template, request, redirect, url_for, current_app, flash, jsonify
from datetime import datetime
from database import get_db
import os
import uuid
from werkzeug.utils import secure_filename
import database
from .report_utils import generate_word_report
# from bs4 import BeautifulSoup  # 删除此行

report_complete_bp = Blueprint('report_complete', __name__)

# 允许上传的图片扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

# 辅助函数：检查文件扩展名
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@report_complete_bp.route('/complete_report')
def index():
    db = get_db()
    sections = db.execute(
        'SELECT id, title, content, display_order FROM report_sections ORDER BY display_order'
    ).fetchall()
    return render_template('report_complete.html', now=datetime.now(), sections=sections)

@report_complete_bp.route('/get_images')
def get_images():
    try:
        db = get_db()
        images = db.execute(
            'SELECT id, section_id, file_name, file_path, caption FROM report_images ORDER BY id DESC'
        ).fetchall()

        result = []
        for image in images:
            # 直接使用file_name构建URL
            image_url = url_for('static', filename=f'images/{image["file_name"]}')
            
            result.append({
                'id': image['id'],
                'section_id': image['section_id'],
                'file_name': image['file_name'],
                'file_path': image['file_path'],
                'caption': image['caption'],
                'url': image_url  # 添加URL字段供前端直接使用
            })

        return jsonify({
            'success': True,
            'images': result
        })
    except Exception as e:
        current_app.logger.error(f'获取图片失败: {str(e)}')
        return jsonify({
            'success': False,
            'error': f'获取图片失败: {str(e)}'
        }), 500

@report_complete_bp.route('/upload_image', methods=['POST'])
def upload_image():
    uploaded_files = []  # 初始化变量
    try:
        # 检查是否有文件上传
        if 'file' not in request.files:
            return jsonify({
                'success': False,
                'message': '未选择图片文件'
            }), 400

        file = request.files['file']
        caption = request.form.get('caption', '')
        section_id = request.form.get('section_id', 1)  # 默认section_id为1

        # 检查文件是否为空
        if file.filename == '':
            return jsonify({
                'success': False,
                'message': '未选择图片文件'
            }), 400

        # 检查文件类型
        if file and allowed_file(file.filename):
            # 生成唯一文件名
            filename = f"report_{uuid.uuid4().hex}_{secure_filename(file.filename)}"
            # 修改保存路径到static/images目录
            filepath = os.path.join(current_app.root_path, 'static', 'images', filename)
            file.save(filepath)
            uploaded_files.append({
                'filename': filename,
                'path': filepath,
                'url': url_for('static', filename=f'images/{filename}')
            })

            # 保存到数据库
            db = get_db()
            db.execute(
                '''INSERT INTO report_images (section_id, file_name, file_path, caption)
                   VALUES (?, ?, ?, ?)''',
                (section_id, filename, f'static/images/{filename}', caption)
            )
            db.commit()

            # 构建图片URL
            image_url = url_for('static', filename=f'images/{filename}')

            return jsonify({
                'success': True,
                'message': '图片上传成功',
                'file': {
                    'filename': filename,
                    'path': f'static/images/{filename}',
                    'url': image_url
                }
            })
        return jsonify({
            'status': 'success',
            'message': f'成功上传{len(uploaded_files)}张图片',
            'files': uploaded_files
        })
    except Exception as e:
        current_app.logger.error(f'上传图片失败: {str(e)}')
        return jsonify({
            'success': False,
            'error': f'上传图片失败: {str(e)}'
        }), 500

@report_complete_bp.route('/export/<format>')
def export(format):
    # 获取选中的报表
    selected_reports = request.args.getlist('reports') or [
        'annual_emission', 'fuel_consumption', 'power', 'thermal'
    ]

    # 获取报告内容（实际实现需从数据库或表单获取）
    report_data = {
        'title': '碳管理排放报告',
        'subtitle': '2023年度可持续发展报告',
        'company': '示例公司',
        'date': datetime.now().strftime('%Y年%m月%d日'),
        'content_sections': [],  # 将从前端编辑器获取
        'images': [],  # 将从上传图片获取
        'selected_reports': selected_reports
    }

    if format == 'pdf':
        return generate_pdf_report(report_data)
    elif format == 'word':
        return generate_word_report(report_data)
    else:
        flash('不支持的导出格式')
        return redirect(url_for('report_complete.index'))

@report_complete_bp.route('/add_section', methods=['POST'])
def add_section():
    # 确保正确获取JSON数据
    if request.is_json:
        data = request.get_json()
        # 添加调试信息：打印接收到的原始数据
        current_app.logger.debug(f"Received add_section data: {data}")
    else:
        return jsonify({'success': False, 'error': '请求格式必须为JSON'}), 400

    # 获取参数（保留原始格式，不做strip处理）
    section_type = data.get('section_type', 'text')
    title = data.get('title', '').strip()
    # 修复：保留content原始格式，不使用strip()避免意外删除内容
    content = data.get('content', '')
    style_json = data.get('style_json', '{}')

    # 修复：调整验证逻辑，允许content包含空白字符但不允许完全为空
    if not title:
        return jsonify({'success': False, 'error': '标题不能为空'}), 400
    if content is None or content.strip() == '':
        return jsonify({'success': False, 'error': '内容不能为空'}), 400

    db = get_db()
    try:
        max_order_result = db.execute('SELECT MAX(display_order) AS max_order FROM report_sections').fetchone()
        max_order = max_order_result['max_order'] if max_order_result['max_order'] is not None else 0

        cursor = db.execute(
            '''INSERT INTO report_sections 
               (section_type, title, content, style_json, display_order) 
               VALUES (?, ?, ?, ?, ?)''',
            (section_type, title, content, style_json, max_order + 1)
        )
        db.commit()

        # 验证插入结果并返回完整数据
        if cursor.rowcount == 0:
            raise Exception('未插入任何数据，请检查数据库连接')

        section_id = cursor.lastrowid
        section = db.execute('SELECT id, title, content FROM report_sections WHERE id = ?', (section_id,)).fetchone()

        return jsonify({
            'success': True,
            'section': {
                'id': section['id'],
                'title': section['title'],
                'content': section['content'],  # 返回保存的content用于前端验证
                'display_order': max_order + 1
            },
            'debug': {
                'received_content_length': len(content),
                'saved_content_length': len(section['content'])
            }
        })
    except Exception as e:
        db.rollback()
        current_app.logger.error(f"保存段落失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'保存失败: {str(e)}',
            'debug': {
                'title_provided': bool(title),
                'content_provided': bool(content),
                'content_length': len(content) if content else 0
            }
        }), 500


@report_complete_bp.route('/update_section', methods=['PUT'])
def update_section():
    data = request.get_json()
    section_id = data.get('section_id')
    title = data.get('title')
    content = data.get('content')
    
    # 移除未使用的HTML解析逻辑引用
    # ===============================
    
    # 修正参数验证逻辑
    if not section_id or not title or not content:
        return jsonify({'success': False, 'error': '段落ID、标题和内容不能为空'}), 400
    
    try:
        db = get_db()
        # 使用content而非body变量
        db.execute(
            'UPDATE report_sections SET title = ?, content = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
            (title, content, section_id)  # 直接使用前端传递的content
        )
        db.commit()
        return jsonify({
            'success': True,
            'debug_info': {
                'received_title': title,
                'content_length': len(content)
            }
        })
    except Exception as e:
        db.rollback()
        current_app.logger.error(f"更新段落失败: {str(e)}")
        return jsonify({'success': False, 'error': f'保存失败: {str(e)}'}), 500
@report_complete_bp.route('/delete_section/<int:section_id>', methods=['DELETE'])
def delete_section(section_id):
    try:
        db = get_db()
        section = db.execute('SELECT id FROM report_sections WHERE id = ?', (section_id,)).fetchone()
        if not section:
            return jsonify({'success': False, 'error': '段落不存在'}), 404

        db.execute('DELETE FROM report_sections WHERE id = ?', (section_id,))
        db.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500


# 添加获取企业基本信息的路由
@report_complete_bp.route('/get_basic_info', methods=['GET'])
def get_basic_info():
    try:
        db = get_db()
        # 假设我们只需要最新的一条企业基本信息
        basic_info = db.execute(
            '''SELECT id, entity_name, entity_type, unified_social_credit_code, 
                      industry, legal_representative, main_products, 
                      report_responsible_person, contact_information 
               FROM report_tables 
               ORDER BY id DESC 
               LIMIT 1'''
        ).fetchone()

        if not basic_info:
            return jsonify({
                'success': True,
                'data': None,
                'message': '暂无企业基本信息数据'
            })

        # 将查询结果转换为字典
        data = {
            'id': basic_info['id'],
            'entity_name': basic_info['entity_name'],
            'entity_type': basic_info['entity_type'],
            'unified_social_credit_code': basic_info['unified_social_credit_code'],
            'industry': basic_info['industry'],
            'legal_representative': basic_info['legal_representative'],
            'main_products': basic_info['main_products'],
            'report_responsible_person': basic_info['report_responsible_person'],
            'contact_information': basic_info['contact_information']
        }

        return jsonify({
            'success': True,
            'data': data
        })
    except Exception as e:
        current_app.logger.error(f"获取企业基本信息失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'获取数据失败: {str(e)}'
        }), 500


@report_complete_bp.route('/save_basic_info', methods=['POST'])
def save_basic_info():
    db = None
    try:
        # 获取JSON数据
        data = request.get_json()

        # 验证必填字段
        required_fields = [
            'entity_name', 'entity_type', 'unified_social_credit_code',
            'industry', 'legal_representative', 'main_products',
            'report_responsible_person', 'contact_information'
        ]

        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({
                    'success': False,
                    'message': f'缺少必填字段: {field}'
                }), 400

        db = get_db()

        # 检查是否已存在企业基本信息记录
        existing_record = db.execute(
            'SELECT id FROM report_tables ORDER BY id DESC LIMIT 1'
        ).fetchone()

        if existing_record:
            # 更新现有记录
            db.execute(
                '''UPDATE report_tables
                   SET entity_name = ?, entity_type = ?, unified_social_credit_code = ?,
                       industry = ?, legal_representative = ?, main_products = ?,
                       report_responsible_person = ?, contact_information = ?
                   WHERE id = ?''',
                (
                    data['entity_name'], data['entity_type'], data['unified_social_credit_code'],
                    data['industry'], data['legal_representative'], data['main_products'],
                    data['report_responsible_person'], data['contact_information'],
                    existing_record['id']
                )
            )
            message = '企业基本信息已更新'
        else:
            # 创建新记录
            db.execute(
                '''INSERT INTO report_tables
                   (entity_name, entity_type, unified_social_credit_code, industry,
                    legal_representative, main_products, report_responsible_person,
                    contact_information, created_at)
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)''',
                (
                    data['entity_name'], data['entity_type'], data['unified_social_credit_code'],
                    data['industry'], data['legal_representative'], data['main_products'],
                    data['report_responsible_person'], data['contact_information']
                )
            )
            message = '企业基本信息已创建'

        db.commit()

        return jsonify({
            'success': True,
            'message': message
        })

    except Exception as e:
        if db:
            try:
                db.rollback()
            except:
                pass
        current_app.logger.error(f'保存企业基本信息失败: {str(e)}')
        return jsonify({
            'success': False,
            'message': f'保存失败: {str(e)}'
        }), 500


@report_complete_bp.route('/delete_image/<int:image_id>', methods=['DELETE'])
def delete_image(image_id):
    try:
        db = get_db()
        # 获取图片信息
        image = db.execute('SELECT file_path FROM report_images WHERE id = ?', (image_id,)).fetchone()
        if not image:
            return jsonify({'success': False, 'error': '图片不存在'}), 404

        # 删除文件
        file_path = os.path.join(current_app.root_path, image['file_path'])
        if os.path.exists(file_path):
            os.remove(file_path)

        # 删除数据库记录
        db.execute('DELETE FROM report_images WHERE id = ?', (image_id,))
        db.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.rollback()
        current_app.logger.error(f'删除图片失败: {str(e)}')
        return jsonify({'success': False, 'error': str(e)}), 500